#include "User.h"
using namespace std;

User::User()
{
    ID = -1;
    name = NULL;
    state = OFFLINE;
    is_connected = false;
    sock_num = -1;
}

void User::set_state(User_state s)
{
    state = s;
}

User_state User::get_state()
{
    return state;
}

bool User::connect_to_server(struct sockaddr_in saddr)
{
    int sock;
    char msg_send[] = "connect", msg_recv[MAX_MSG_LEN];
    string connect_fail = "fail";
    string connect_sucess = "accept";
    if (state != OFFLINE)
    {
	return true;
    }

    sock = make_client_socket();
    if (sock == -1)
    {
        return false;
    }
    sock_num = sock;
    if (sendto(sock, msg_send, strlen(msg_send), 0, &saddr, sizeof(saddr)) == -1)
    {
        return false;
    }
    
    if (recvfrom(sock, msg_recv, MAX_MSG_LEN, 0, NULL, NULL) == -1)
    {
        return false;
    }

    if (connect_fail == msg_recv)
    {
        return false;
    }
    else if (connect_sucess == msg_recv)
    {
        return true;
    }
    else
    {
        return false;
    }
}

void User::disconnect()
{
    send_msg("disconnect");
    
}

int send_msg(string message)
{
    const char *buf = message.c_str();
    if (sendto(sock_num, message.c_str(), message.size(), 0, 
                      &saddr, sizeof(saddr)) == -1)
    {
        return -1;
    }
    return 0;
}

string get_reply()
{
    char buf[MAX_MSG_LEN];
    string reply;
    
    if (recvfrom(sock_num, buf, MAX_MSG_LEN, 0, NULL, NULL) == -1)
    {
        return NULL;
    }
    reply = buf;
    return reply;
}
